package com.woniuxy.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.admin.client.GoodsFeignClient;
import com.woniuxy.admin.dto.AdminAccountPageDto;
import com.woniuxy.admin.entity.*;
import com.woniuxy.admin.exception.AdminException;
import com.woniuxy.admin.exception.PawnShopException;

import com.woniuxy.admin.dto.PawnShopDto;
import com.woniuxy.admin.form.InsertPawnShopForm;
import com.woniuxy.admin.form.InsertShopAssistantForm;
import com.woniuxy.admin.form.UpdatePawnShopForm;
import com.woniuxy.admin.mapper.*;
import com.woniuxy.admin.service.AdminAccountService;
import com.woniuxy.admin.service.AdminInfoService;
import com.woniuxy.admin.service.AdminRoleService;
import com.woniuxy.admin.service.PawnShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.woniuxy.core.util.StateNum;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ...
 * @since 2024年05月22日
 */
@Service
public class PawnShopServiceImpl extends ServiceImpl<PawnShopMapper, PawnShop> implements PawnShopService {

    @Resource
    private PawnWarehouseMapper pawnWarehouseMapper;
    @Resource
    private PawnShopWarehouseMapper pawnShopWarehouseMapper;

    @Resource
    private AdminInfoMapper adminInfoMapper;
    @Resource
    private AdminAccountService adminAccountService;
    @Resource
    private AdminRoleService adminRoleService;
    @Resource
    private AdminInfoService adminInfoService;
    @Resource
    private AdminAccountMapper adminAccountMapper;

    @Resource
    private GoodsFeignClient goodsFeignClient;



    /**
     * 分页查询门店信息
     * @param pageNum 分页页数
     * @param pageSize 每页个数
     * @return
     */
    @Override
    public Page<PawnShopDto> loadAllPawnShop(Integer pageNum, Integer pageSize,String condition) {
        Page<PawnShop>page=new Page<>(pageNum,pageSize);
        QueryWrapper<PawnShop> wrapper1 = new QueryWrapper<>();
        if(condition!=null&&!condition.equals("")){
            wrapper1.like("shop_name",condition).or();
            wrapper1.like("address",condition);
        }
        this.page(page,wrapper1);
        List<PawnShop> records = page.getRecords();
        List<PawnShopDto>dtos=new ArrayList<>();
        if(records!=null&&records.size()>0){
            for (PawnShop pawnShop : records) {
                PawnShopDto pawnShopDto = BeanUtil.toBean(pawnShop, PawnShopDto.class);
                QueryWrapper<PawnShopWarehouse>wrapper=new QueryWrapper<>();
                wrapper.eq("shop_id",pawnShop.getShopId());
                List<PawnShopWarehouse> pawnShopWarehouses = pawnShopWarehouseMapper.selectList(wrapper);
                if(pawnShopWarehouses!=null&&pawnShopWarehouses.size()>0){
                    for (PawnShopWarehouse pawnShopWarehouse : pawnShopWarehouses) {
                        PawnWarehouse pawnWarehouse = pawnWarehouseMapper.selectById(pawnShopWarehouse.getWarehouseId());
                        pawnShopDto.getPawnWarehousesList().add(pawnWarehouse);
                        pawnShopDto.getWarehouseIds().add(pawnWarehouse.getWarehouseId());
                    }
                }
                dtos.add(pawnShopDto);
            }
        }
        Page<PawnShopDto>pages=new Page<>();
        pages.setPages(page.getPages());
        pages.setTotal(page.getTotal());
        pages.setCurrent(page.getCurrent());
        pages.setSize(page.getSize());
        pages.setRecords(dtos);
        return pages;
    }

    /**
     * 新增门店
     * @param form 新增门店参数
     */

    @Override
    public void insertPawnShop(InsertPawnShopForm form) {
        List<PawnShop> pawnShops = this.list();
        for (PawnShop pawnShop : pawnShops) {
            if(pawnShop.getShopName().equals(form.getShopName())){
                throw new PawnShopException(30001,"门店名重复");
            }
        }
        List<Integer> accounts = adminAccountService.selectAccountsByRoleId(3);
        if (!accounts.contains(form.getShopBossId())) throw new AdminException(10009,"门店店长Id不存在");
        QueryWrapper<PawnShop>wrapper=new QueryWrapper<>();
        wrapper.eq("shop_boss_id",form.getShopBossId());
        PawnShop pawnShop1 = this.getOne(wrapper);
        if(pawnShop1!=null) throw new PawnShopException(100002,"门店老板已被绑定");
        AdminInfo adminInfo = adminInfoMapper.selectOne(new QueryWrapper<AdminInfo>().eq("account_id", form.getShopBossId()));
        PawnShop pawnShop = BeanUtil.toBean(form, PawnShop.class);
        pawnShop.setState(0);
        pawnShop.setContact(adminInfo.getRealName());
        this.save(pawnShop);
    }

    /**
     * 更新门店信息
     * @param form 修改门店参数
     */
    @Override
    public void updatePawnShop(UpdatePawnShopForm form) {
        PawnShop pawnShop = this.getById(form.getShopId());
        Integer oleShopBoosId=pawnShop.getShopBossId();
        if(pawnShop==null) throw new PawnShopException(30002,"门店不存在");
        pawnShop.setShopName(form.getShopName());
        pawnShop.setShopPhone(form.getShopPhone());
        pawnShop.setAddress(form.getAddress());
        if(pawnShop.getShopBossId()!=form.getShopBossId()){
            AdminAccount account = adminAccountMapper.selectById(form.getShopBossId());
            if(account.getState()!=0) throw new PawnShopException(10001,"店长状态有误");
            AdminInfo adminInfo = adminInfoMapper.selectById(form.getShopBossId());
            if(adminInfo==null) throw new PawnShopException(1000,"店长不存在");
            pawnShop.setShopBossId(form.getShopBossId());
            pawnShop.setContact(adminInfo.getRealName());
            goodsFeignClient.updateProcessByBoss(oleShopBoosId,form.getShopBossId());
        }
        this.updateById(pawnShop);
    }

    /**
     * 更新门店状态
     * @param shopId 门店id
     * @param state 状态码
     */
    @Override
    public void updatePawnShopState(Integer shopId, Integer state) {
        PawnShop pawnShop = this.getById(shopId);
        if(pawnShop==null) throw new PawnShopException(30002,"门店不存在");
        if(state!=0&&state!=1) throw new PawnShopException(10002,"状态有误");
        pawnShop.setState(state);
        this.updateById(pawnShop);
    }

    /**
     * 根据门店Id查找门店
     * @param shopId 门店id
     * @return
     */
    @Override
    public PawnShopDto selectPawnShopById(Integer shopId) {
        PawnShop pawnShop = this.getById(shopId);
        if(pawnShop==null) throw new PawnShopException(30001,"门店不存在");
        PawnShopDto pawnShopDto = BeanUtil.toBean(pawnShop, PawnShopDto.class);
        QueryWrapper<PawnShopWarehouse>wrapper=new QueryWrapper<>();
        wrapper.eq("shop_id",pawnShop.getShopId());
        List<PawnShopWarehouse> pawnShopWarehouses = pawnShopWarehouseMapper.selectList(wrapper);
        if(pawnShopWarehouses!=null&&pawnShopWarehouses.size()>0) {
            for (PawnShopWarehouse pawnShopWarehouse : pawnShopWarehouses) {
                PawnWarehouse pawnWarehouse = pawnWarehouseMapper.selectById(pawnShopWarehouse.getWarehouseId());
                pawnShopDto.getPawnWarehousesList().add(pawnWarehouse);
                pawnShopDto.getWarehouseIds().add(pawnWarehouse.getWarehouseId());
            }
        }
        return pawnShopDto;
    }

    /**
     * 新增门店店员  存json字符串
     *
     */
    @Override
    public void insertShopAssistant(InsertShopAssistantForm form) {
        List<Integer> assistantIds = adminAccountService.selectAccountsByRoleId(4);
       if(!assistantIds.containsAll(form.getAccounts())) throw new PawnShopException(20002,"有店员不存在");
        PawnShop pawnShop = this.getById(form.getShopId());
        if(pawnShop==null) throw new PawnShopException(30002,"门店不存在");
        String shopAssIstantId = pawnShop.getShopAssIstantId();
        List <Integer> shopAssIstantIds = JSONObject.parseArray(shopAssIstantId, Integer.class);
        if(shopAssIstantIds!=null&&shopAssIstantIds.size()>0) {
            for (Integer account : form.getAccounts()) {
                for (Integer id : shopAssIstantIds) {
                    if(account==id){
                        throw new PawnShopException(20001,"店员已存在");
                    }
                }
            }
            shopAssIstantIds.addAll(form.getAccounts());
            String str = JSONUtil.toJsonStr(shopAssIstantIds);
            pawnShop.setShopAssIstantId(str);
            this.updateById(pawnShop);
        }else {
            List<Integer>shopAssIstantIdss=new ArrayList<>();
            shopAssIstantIdss.addAll(form.getAccounts());
            String str = JSONUtil.toJsonStr(shopAssIstantIdss);
            pawnShop.setShopAssIstantId(str);
            this.updateById(pawnShop);
        }

    }

    /**
     * 通过账号id查门店
     * @param accountId 账号ID
     * @return 门店对象
     */
    @Override
    public PawnShop findShopByAccountId(Integer accountId) throws Exception {
        AdminRole adminRole = adminRoleService.loadAllRoleByAccountId(accountId);
        QueryWrapper<PawnShop> wrapper = new QueryWrapper<>();
        if (adminRole.getRoleId()==3){
            //店长
            wrapper.eq("shop_boss_id",accountId);
        }else if(adminRole.getRoleId()==4){
            //店员
            wrapper.like("shop_assistant_id",accountId);
        }else{
            throw new Exception("角色异常");
        }
        return getOne(wrapper);
    }

    /**
     * 根据门店Id查询店员信息
     *
     * @param shopId
     * @return
     */
    @Override
    public List<AdminAccountPageDto> findShopAssistantByShopId(Integer shopId,Integer is) {
        if(ObjectUtil.isEmpty(is)){
            is=0;
        }
        PawnShop pawnShop = this.getById(shopId);
        if(pawnShop==null) throw new PawnShopException(10002,"店铺不存在");
        String shopAssIstantIds = pawnShop.getShopAssIstantId();
        if(shopAssIstantIds==null) return null;
        List<Integer> list = JSONObject.parseArray(shopAssIstantIds, Integer.class);
        List<AdminAccountPageDto>dtos=new ArrayList<>();
        List<AdminAccountPageDto>allDtos=new ArrayList<>();
        for (Integer accountId : list) {
            AdminAccountPageDto dto = adminInfoService.findAdminInfoByAccountId(accountId);
            if(is==1){
                if (dto.getState()== StateNum.ACCOUNT_STATE_NORMAL){
                    dtos.add(dto);
                }
            }
            allDtos.add(dto);
        }
        return is==1?dtos:allDtos;
    }

    /**
     * 查询所有未绑定店员信息
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<AdminAccountPageDto> findAllShopAssistant(Integer pageNum, Integer pageSize) {
        List<Integer> list = adminAccountService.selectAccountsByRoleId(4);
        //if(list==null||list.size()==0) return null;
        List<PawnShop> pawnShops = this.list();
        for (PawnShop pawnShop : pawnShops) {
            if(ObjectUtil.isNotEmpty(pawnShop.getShopAssIstantId())){
                List<Integer> list1 = JSONObject.parseArray(pawnShop.getShopAssIstantId(), Integer.class);
                list.removeAll(list1);
            }
        }
        //
        Page <AdminAccount>page=new Page<>(pageNum,pageSize);
        QueryWrapper<AdminAccount> wrapper=new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(list)){
            wrapper.in("account_id",list);
        }
        adminAccountMapper.selectPage(page,wrapper);
        if(ObjectUtil.isEmpty(list)){
            page.setRecords(null);
        }
        List<AdminAccountPageDto>lists=new ArrayList<>();
        if(page.getRecords()!=null&&page.getRecords().size()>0){
            for (AdminAccount adminAccount : page.getRecords()) {
                AdminAccountPageDto adminAccountPageDto = BeanUtil.toBean(adminAccount, AdminAccountPageDto.class);
                AdminInfo adminInfo = adminInfoMapper.selectOne(new QueryWrapper<AdminInfo>().eq("account_id", adminAccount.getAccountId()));
                BeanUtil.copyProperties(adminInfo,adminAccountPageDto);
                String s = adminRoleService.loadAllRoleNameByAccountId(adminAccount.getAccountId());
                adminAccountPageDto.setRole(s);
                lists.add(adminAccountPageDto);
            }
        }
        Page<AdminAccountPageDto>pages=new Page<>();
        pages.setPages(page.getPages());
        pages.setSize(page.getSize());
        pages.setCurrent(page.getCurrent());
        pages.setTotal(page.getTotal());
        pages.setRecords(lists);
        return pages;
    }


}
